﻿using System.Windows.Controls;
using GalaSoft.MvvmLight.Messaging;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Tfs.OnTheRoad.Model;
using Tfs.OnTheRoad.Pages;
using Tfs.OnTheRoad.ViewModel;
namespace Tfs_OnTheRoad
{
    /// <summary>
    /// Project Overview Page
    /// </summary>
    public partial class ProjectOverviewPage : BasePage
    {
        public ProjectOverviewPage()
        {
            InitializeComponent();
        }
        ProjectOverviewViewModel ViewModel = null;

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            //We set it to -1 to avoid that the selectionChanged event is not being triggered if we are coming back
            //to this page(back button)
            BuildsListBox.SelectedIndex = -1;
            BranchesListBox.SelectedIndex = -1;
            QueriesListBox.SelectedIndex = -1;

            var currentProject = PhoneApplicationService.Current.State["CurrentProject"] as Project;
            var loadedViewModel = this.DataContext as ProjectOverviewViewModel;

            if (loadedViewModel==null && currentProject != null)
            {                
                ViewModel = new ProjectOverviewViewModel(currentProject);
                this.DataContext = ViewModel;
                Messenger.Default.Send<PhoneApplicationPage>(this, "RestoreState");   
                buildsGrid.DataContext = ViewModel.BuildListViewModel;
                changesetsItem.DataContext = ViewModel.ChangesetListViewModel;
                queriesGrid.DataContext = ViewModel.QueryListViewModel;
                branchesGrid.DataContext = ViewModel.BranchListViewModel;
                WorkItemsChart.DataContext = ViewModel.WorkItemsChartViewModel;
            }
            LoadCurrentPivotItem();
        }

        private void LoadCurrentPivotItem()
        {
            if (projectPanorama.SelectedIndex==-1 || projectPanorama.SelectedItem == summaryItem)
            {
                ViewModel.LoadSummary();
            }
            else if (projectPanorama.SelectedItem == buildsItem)
            {
                ViewModel.LoadBuilds();
            }
            else if (projectPanorama.SelectedItem == changesetsItem)
            {
                ViewModel.LoadChangesets();
            }
            else if (projectPanorama.SelectedItem == queriesItem)
            {
                ViewModel.LoadQueries();
            }
            else if (projectPanorama.SelectedItem == branchesItem)
            {
                ViewModel.LoadBranches();
            }
        }
        
        private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            LoadCurrentPivotItem();  
        }
    }
}
